import React, { useState, useRef, useEffect } from 'react';
import classnames from 'classnames';
import request from '@/utils/request';
import './index.less';
// import fetch from '../../utils/fetch';

// import { checkMobileIsOk } from '../../services/user';

type TOwnProps = {
  payload?: (() => any) | any;
  url?: string;
  /**
   * onBeforeSend钩子函数
   * 返回true / false
   * false 不执行
   */
  onBeforeSend?: (data?: any) => Promise<Boolean> | boolean;

  /**
   * onAfterSend 钩子函数
   * 发送请求后的数据返回
   * false 不执行
   */
  onAfterSend?: (data?: any) => Promise<Boolean> | boolean;
  onEnd?: () => void;
  active: Boolean;
  time?: number;
  classNames?: string;
  text?: string;
  method?: 'POST' | 'GET';
  requestType?: 'json' | 'form';
};
type State = {
  status: 'send' | 'sent' | 'resend';
  cutdownTime: number;
};

const Index: React.FC<TOwnProps> = ({
  time,
  active,
  classNames,
  onBeforeSend,
  onAfterSend,
  onEnd,
  url,
  payload,
  text,
  method,
  requestType,
}) => {
  const [status, setStatus] = useState<State['status']>('send');
  const [cutdownTime, setCutdownTime] = useState(() => time || 60);

  const timer = useRef(1);

  /**
   * 清除定时器
   */
  useEffect(() => {
    return () => clearInterval(timer.current as any);
  }, []);

  const getStatus = () => {
    if (status === 'send') {
      return text;
    }
    if (status === 'sent') {
      return `${cutdownTime}s`;
    }
    if (status === 'resend') {
      return `重新发送`;
    }
    return '';
  };

  const cutdown = () => {
    if (status === 'sent') return;
    /**
     * 发送了
     */
    setStatus('sent');
    let num = cutdownTime;
    timer.current = setInterval(() => {
      if (num <= 1) {
        clearInterval(timer.current as any);
        setStatus('resend');
        setCutdownTime(cutdownTime);
        if (onEnd && typeof onEnd === 'function') {
          onEnd();
        }
        return;
      }
      // eslint-disable-next-line no-plusplus
      setCutdownTime(--num);
    }, 1000) as any;
  };

  const send = async () => {
    // onBeforeSend的钩子函数
    if (typeof onBeforeSend === 'function') {
      const onBeforeSendFlag = await onBeforeSend();
      if (onBeforeSendFlag === false) return;
    }
    if (!active || status === 'sent') return;

    if (url) {
      const options = {
        method,
        requestType,
      } as any;
      const payloadData = typeof payload === 'function' ? payload() : payload;
      if (method === 'POST') {
        options.data = payloadData;
      } else {
        options.params = payloadData;
      }
      const data = await request(url, options);
      // 返回数据给 onAfterSend 的钩子函数
      if (typeof onAfterSend === 'function') {
        const onAfterSendFlag = await onAfterSend(data);
        if (onAfterSendFlag === false) return;
      }
      if (!onAfterSend && !data.success) return;
    }

    /**
     * 开始倒计时
     */
    cutdown();
  };

  return (
    <div
      className={classnames('hr-sendcode', classNames, {
        active: active || status === 'sent',
      })}
      onClick={send}
    >
      <div className="hr-sendcode-status">{getStatus()}</div>
    </div>
  );
};
Index.defaultProps = {
  text: '发送验证码',
  method: 'POST',
  requestType: 'json',
};

export default Index;
